package com.ccit.controller;

import com.alibaba.fastjson.JSONObject;
import com.ccit.model.User;
import com.ccit.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class loginController {

    @Autowired
    private UserService UserServiceimpl;

    /**
     * 登陆页面
     * @return
     */
    @RequestMapping("login")
        private String login(){
        return "login";
    }

    /**
     * 登陆验证页面
     */
    @RequestMapping(value = "verify")
    private String verify(Model model,User user){
        //获取当前用户的shiro信息
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            return "redirect:user/index";
        }
        //token安全令牌
        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(),user.getPassword());
        try {
            //调用登录,会自动进入realm
            currentUser.login(token);
//            Session session=currentUser.getSession();
//            session.setAttribute("subject", currentUser);
            //登陆成功
            return "redirect:/user/index";

            //登陆失败.抛出异常
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "验证失败");
            return "login";
        }
    }


}
